'use strict';

const Service = require('egg').Service;

module.exports = class CategoryService extends Service {
  // Update Categories ///////////////////////////////////////////////////////////////////
  async updateCategories() {
    const func = this.ctx.helper;
    const input = this.ctx.request.body;
    const connBlog = this.ctx.app.connBlog;
    const theCache = this.ctx.app.theCache;

    // Save changes ------------------------------------------------
    if (this.ctx.request.query.act === 'update') {
      // Set all to false then set selected ones to hidden
      await connBlog.updateSQL('blog_category', 'cat_hidden=false', 'cat_id>0');
      if (input.hidden) {
        const arrHidden = input.hidden.split(',');
        for (let i = 0; i < arrHidden.length; i++) {
          arrHidden[i] = func.checkInt(arrHidden[i]);
        }
        await connBlog.updateSQL('blog_category', 'cat_hidden=true', 'cat_id IN (' + arrHidden.join(',') + ')');
      }

      // Set all to false then set selected ones to locked
      await connBlog.updateSQL('blog_category', 'cat_locked=false', 'cat_id>0');
      if (input.locked) {
        const arrLocked = input.locked.split(',');
        for (let i = 0; i < arrLocked.length; i++) {
          arrLocked[i] = func.checkInt(arrLocked[i]);
        }
        await connBlog.updateSQL('blog_category', 'cat_locked=true', 'cat_id IN (' + arrLocked.join(',') + ')');
      }

      // Update Data
      const arrID = input.id.split(',');
      const arrName = input.name.split(',');
      const arrOrder = input.order.split(',');
      for (let i = 0; i < arrID.length; i++) {
        // Check data
        arrID[i] = func.checkInt(arrID[i]);
        arrName[i] = func.trim(arrName[i]);
        arrOrder[i] = func.checkInt(arrOrder[i]);
        if (arrName[i].length < 1 || arrName[i].length > 50) arrID[i] = -1;

        // Update DB
        const arrData = { cat_name: arrName[i],
          cat_order: arrOrder[i] };
        if (arrID[i] != -1) await connBlog.update('blog_category', arrData, 'cat_id=' + arrID[i]);
        // Insert new category
        if (arrID[i] == 0) {
          arrData.cat_hidden = !!input.newhidden;
          arrData.cat_locked = !!input.newlocked;
          await connBlog.insert('blog_category', arrData);
        }
      }
      return;
    }

    // Move Articles --------------------------------
    if (this.ctx.request.query.act == 'move') {
      if (!input.selected) return;
      const arrSelected = input.selected.split(',');
      for (let i = 0; i < arrSelected.length; i++) {
        arrSelected[i] = func.checkInt(arrSelected[i]);
        if (arrSelected[i] < 1) {
          arrSelected.splice(i, 1);
          i--;
        }
      }
      if (arrSelected.length > 0) {
        if (!input.target) {
          outputCatMoveTarget(arrSelected);
        } else {
          input.target = await theCache.getCategoryByID(func.checkInt(input.target));
          if (input.target.id > 0) {
            await connBlog.updateSQL('blog_article', 'log_catID=' + input.target.id, 'log_catID IN (' + arrSelected.join(',') + ')');
            // Resync Article Counter
            await connBlog.updateSQL('blog_category', 'cat_articleCount=0', 'cat_id IN (' + arrSelected.join(',') + ')');
            const tmpA = await connBlog.query('SELECT count(log_id) as cnt FROM blog_article WHERE log_catid=' + input.target.id);
            await connBlog.updateSQL('blog_category', 'cat_articleCount=' + tmpA[0].cnt, 'cat_id=' + input.target.id);
            await theCache.loadCategories();
            await theCache.loadArticles();
          }
        }
      }
      return;
    }

    // Delete Categories --------------------------------
    if (this.ctx.request.query.act == 'delete') {
      if (!input.selected) return;
      let arrSelected = input.selected.split(',');
      for (let i = 0; i < arrSelected.length; i++) {
        arrSelected[i] = func.checkInt(arrSelected[i]);
        if (arrSelected[i] < 1) {
          arrSelected.splice(i, 1);
          i--;
        }
      }
      // Do delete
      if (arrSelected.length > 0) {
        arrSelected = arrSelected.join(',');
        await connBlog.doDelete('blog_article tLog, blog_comment tComm', 'tComm.log_id=tLog.log_id AND tLog.log_catID IN (' + arrSelected + ')', 'tComm.*');
        await connBlog.doDelete('blog_article tLog, blog_trackback tTB', 'tTB.log_id=tLog.log_id AND tLog.log_catID IN (' + arrSelected + ')', 'tTB.*');
        await connBlog.doDelete('blog_article', 'log_catID IN (' + arrSelected + ')');
        await connBlog.doDelete('blog_category', 'cat_id IN (' + arrSelected + ')');
        let tmpA = await connBlog.query('SELECT count(log_id) as cnt FROM blog_article');
        await connBlog.updateSQL('blog_settings', 'set_value0=' + tmpA[0].cnt, "set_name='counterArticle'");
        tmpA = await connBlog.query('SELECT count(comm_id) as cnt FROM blog_aomment');
        await connBlog.updateSQL('blog_settings', 'set_value0=' + tmpA[0].cnt, "set_name='counterComment'");
        tmpA = await connBlog.query('SELECT count(tb_id) as cnt FROM blog_trackback');
        await connBlog.updateSQL('blog_settings', 'set_value0=' + tmpA[0].cnt, "set_name='counterTrackback'");
        await theCache.loadSettings();
        await theCache.loadCategories();
        await theCache.loadArticles();
      }
      return;
    }

  }
};
